package com.jack006.files.controller;

import com.jack006.api.controller.files.FileUploadControllerApi;
import com.jack006.exception.GraceException;
import com.jack006.files.resource.FileResource;
import com.jack006.files.service.UploaderService;
import com.jack006.grace.result.GraceJSONResult;
import com.jack006.grace.result.ResponseStatusEnum;
import com.jack006.pojo.bo.NewAdminBO;
import com.jack006.utils.FileUtils;
import com.jack006.utils.extend.AliImageReviewUtils;
import com.mongodb.client.gridfs.GridFSBucket;
import com.mongodb.client.gridfs.GridFSFindIterable;
import com.mongodb.client.gridfs.model.GridFSFile;
import com.mongodb.client.model.Filters;
import org.apache.commons.lang3.StringUtils;
import org.bson.types.ObjectId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import sun.misc.BASE64Decoder;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.ByteArrayInputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.util.ArrayList;
import java.util.List;

/**
 * @Classname FileUploadController
 * @Description 文件上传控制类
 * @Date 2021-06-17 22:29
 * @Created by jack
 */
@RestController
public class FileUploadController implements FileUploadControllerApi {

    final static Logger LOGGER = LoggerFactory.getLogger(FileUploadController.class);

    public static final String FAILED_IMAGE_URL = "https://imooc-news.oss-cn-shanghai.aliyuncs.com/image/faild.jpeg";


    @Autowired
    private UploaderService uploaderService;
    @Autowired
    private FileResource fileResource;
    @Autowired
    private AliImageReviewUtils aliImageReviewUtils;
    @Autowired
    private GridFSBucket gridFSBucket;

    @Override
    public GraceJSONResult uploadFace(String userId,
                                      MultipartFile file) throws Exception {

        if (userId == null) {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.USER_ID_IS_NULL_ERROR);
        }
        String path = null;
        if (file != null) {
            // 上传文件名称
            String fileName = file.getOriginalFilename();
            // 判断文件名不能为空
            if (StringUtils.isNotBlank(fileName)) {
                String[] fileNameArr = fileName.split("\\.");
                // 获得文件后缀
                String suffix = fileNameArr[(fileNameArr.length - 1)];
                // 判断后缀是否符合预定义规范
                if (!suffix.equalsIgnoreCase("png") &&
                        !suffix.equalsIgnoreCase("jpg") &&
                        !suffix.equalsIgnoreCase("jpeg")) {
                    return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_FORMATTER_FAILD);
                }


                // 执行上传
                path = uploaderService.uploadFdfs(file, suffix);
                // path = uploaderService.uploadOSS(file, userId,suffix);

            } else {
                GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
            }
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_NULL_ERROR);
        }

        LOGGER.info("path= " + path);

        String finalPath;
        if (StringUtils.isNotBlank(path)) {
            finalPath = fileResource.getHost() + path;
        } else {
            return GraceJSONResult.errorCustom(ResponseStatusEnum.FILE_UPLOAD_FAILD);
        }
        // 图片审核
        // return GraceJSONResult.ok(doAliImageReview(finalPath));
        return GraceJSONResult.ok(finalPath);
    }


    @Override
    public GraceJSONResult uploadSomeFiles(String userId, MultipartFile[] files) throws Exception {
        // 声明 list,用户存放多个图片的地址路径，返回前端
        List<String> imageUrlList = new ArrayList<>();
        if (files != null && files.length > 0) {
            for (MultipartFile file : files) {
                String path = null;
                if (file != null) {
                    // 上传文件名称
                    String fileName = file.getOriginalFilename();
                    // 判断文件名不能为空
                    if (StringUtils.isNotBlank(fileName)) {
                        String[] fileNameArr = fileName.split("\\.");
                        // 获得文件后缀
                        String suffix = fileNameArr[(fileNameArr.length - 1)];
                        // 判断后缀是否符合预定义规范
                        if (!suffix.equalsIgnoreCase("png") &&
                                !suffix.equalsIgnoreCase("jpg") &&
                                !suffix.equalsIgnoreCase("jpeg")) {
                            continue;
                        }
                        // 执行上传
                        path = uploaderService.uploadFdfs(file, suffix);
                    } else {
                        continue;
                    }
                } else {
                    continue;
                }

                String finalPath;
                if (StringUtils.isNotBlank(path)) {
                    finalPath = fileResource.getHost() + path;
                    // 放入到 ImageList 之前需要做图片审核
                    // return GraceJSONResult.ok(doAliImageReview(finalPath));
                    imageUrlList.add(finalPath);
                } else {
                    continue;
                }
            }
        }
        return GraceJSONResult.ok(imageUrlList);

    }

    private String doAliImageReview(String pendingImageUrl) {
        boolean result = false;

        try {
            result = aliImageReviewUtils.reviewImage(pendingImageUrl);
        } catch (Exception e) {
            e.printStackTrace();
        }

        if (!result) {
            return pendingImageUrl;
        }
        return pendingImageUrl;
    }

    @Override
    public GraceJSONResult uploadToGridFS(NewAdminBO newAdminBO) throws Exception {

        // 获得图片的 Base64字符串
        String file64 = newAdminBO.getImg64();
        // 将 base64 字符串转换为 byte 数组
        byte[] bytes = new BASE64Decoder().decodeBuffer(file64.trim());
        // 转换为输入流
        ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(bytes);
        // 上传到 GridFS 中
        ObjectId fileId = gridFSBucket.uploadFromStream(newAdminBO.getUsername() + ".png", byteArrayInputStream);
        // 获得文件的主键 ID
        String fileIdStr = fileId.toString();
        return GraceJSONResult.ok(fileIdStr);
    }

    @Override
    public void readInGridFS(String faceId,
                             HttpServletRequest request,
                             HttpServletResponse response) throws Exception {

        // 0. 判断参数
        if (StringUtils.isBlank(faceId) || faceId.equalsIgnoreCase("null")) {
            GraceException.display(ResponseStatusEnum.ADMIN_FACE_NULL_ERROR);
        }

        //1、从 GridFs 中读取图片
        File adminFace = readGridFSByFaceId(faceId);

        // 2、把人脸图片输出到浏览器
        FileUtils.downloadFileByStream(response, adminFace);
    }

    private File readGridFSByFaceId(String faceId) throws Exception {

        GridFSFindIterable gridFSFiles = gridFSBucket.find(Filters.eq("_id", new ObjectId(faceId)));
        GridFSFile gridFSFile = gridFSFiles.first();
        if (gridFSFile == null) {
            GraceException.display(ResponseStatusEnum.FILE_NOT_EXIST_ERROR);
        }

        String fileName = gridFSFile.getFilename();
        LOGGER.info("人脸图片：" + fileName);

        // 获取文件流，保存文件到本地或者服务器临时目录
        File fileTemp = new File("/Users/jack/docker/mongo");
        if (!fileTemp.exists()) {
            boolean mkdirs = fileTemp.mkdirs();
            LOGGER.info("文件创建" + mkdirs);
        }

        File myFile = new File("/Users/jack/docker/mongo/" + fileName);

        // 创建文件的输出流
        FileOutputStream fileOutputStream = new FileOutputStream(myFile);

        // 下载到服务器或者本地
        gridFSBucket.downloadToStream(new ObjectId(faceId), fileOutputStream);

        return myFile;

    }
}
